package cn.sunlight.college.oss.service.impl;

import cn.sunlight.college.oss.service.OSSService;
import cn.sunlight.college.oss.utils.ConstantPropertiesUtils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @ClassName OSSServiceImpl
 * @Description 上传头像service实现
 * @Author liugang
 * @Date 2021/6/12 ~ 11:47 下午
 * @Version V1.0
 */
@Service
public class OSSServiceImpl implements OSSService {

    @Override
    public String uploadFileAvatar(MultipartFile file) {

        //工具类获取值
        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        try {

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            InputStream putObject = file.getInputStream();
            //获取文件名称
            String original = file.getOriginalFilename();
            String filePath = new DateTime().toString("yyyy/MM/dd");
            String filename = UUID.randomUUID().toString().replaceAll("-","");
            String fileType = original.substring(original.lastIndexOf("."));
            String newName=filePath+"/"+filename+fileType;
            ossClient.putObject(bucketName, newName, putObject);

            // 关闭OSSClient。
            ossClient.shutdown();

            //把上传之后的路径返回
            //https://sunlight-college.oss-cn-beijing.aliyuncs.com/cerwvefw23.jpg
            String url="https://" + bucketName + "." + endpoint + "/" + newName;
            return url;
        }catch (IOException e){
            e.printStackTrace();
            return null;
        }

    }


}
